using System;
using System.Collections;

namespace Sedna.Core.Controller
{
	public class SuperTypeBasedExceptionHandlerMatcher : IExceptionHandlerMatcher
	{

		private ArrayList exceptionHandlers = new ArrayList();

		private TypesComparer comparer = new TypesComparer(true);

		public IList ExceptionHandlers
		{
			get { return exceptionHandlers; }
			set
			{
				exceptionHandlers = (ArrayList)value;//fucking .Net collections!!!
				exceptionHandlers.Sort(comparer);
			}
		}

		public virtual IExceptionHandler Match(Exception exception)
		{
			return Match(exception, exceptionHandlers);
		}

		public virtual IExceptionHandler Match(Exception exception, IList exceptionHandlers)
		{
			if(exceptionHandlers == null || exceptionHandlers.Count == 0)
			{
				return null;
			}
			((ArrayList)exceptionHandlers).Sort(comparer);//once more fucking .Net collections;
			foreach(IExceptionHandler exceptionHandler in exceptionHandlers)
			{
				if(IsMatching(exception, exceptionHandler))
				{
					return exceptionHandler;
				}
			}
			return null;
		}

		protected virtual bool IsMatching(Exception exception, IExceptionHandler exceptionHandler)
		{
			return exceptionHandler.ExceptionType.IsAssignableFrom(exception.GetType());
		}
	}
}
